package com.android.bookgarden.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.bookgarden.MyApplication;
import com.android.bookgarden.R;
import com.android.bookgarden.apis.Apis;
import com.android.bookgarden.base.BaseActivity;
import com.android.bookgarden.bean.DataBean;
import com.android.bookgarden.bean.SmsMode;
import com.android.bookgarden.bean.UserInfo;
import com.android.bookgarden.bean.WXLoginBean;
import com.android.bookgarden.constract.RealtConstract;
import com.android.bookgarden.db.XutilsDataDao;
import com.android.bookgarden.network.HttpType;
import com.android.bookgarden.persenter.BasePersenter;
import com.android.bookgarden.utli.JsonUitl;
import com.android.bookgarden.utli.LogUtil;
import com.android.bookgarden.utli.SpUtils;
import com.android.bookgarden.utli.Utlis;
import com.android.bookgarden.views.LoadingDialog;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Create by zouqh
 * on 2018/11/28
 **/
public class BundTellActivity extends BaseActivity implements View.OnClickListener, RealtConstract.View {

    @BindView(R.id.close)
    ImageView close;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @BindView(R.id.ritgh_text)
    TextView ritghText;
    @BindView(R.id.telPhone)
    EditText telPhone;
    @BindView(R.id.sendCode)
    TextView sendCode;
    @BindView(R.id.smsCode)
    EditText smsCode;
    @BindView(R.id.loinBut)
    TextView loinBut;
    private int recLen = 61;
    private RealtConstract.Presenter presenter;
    private XutilsDataDao dataDao;
    private List<SmsMode> list;
    private String msgCode;
    private WXLoginBean wxLoginBean;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close:
                finish();
                break;

            case R.id.sendCode:
                sendMsg();
                break;

            case R.id.loinBut:
                saveUser();
                break;
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_bund_tel;
    }

    @Override
    protected void initView() {
        titleText.setText("绑定手机");
        wxLoginBean = (WXLoginBean) getIntent().getSerializableExtra("wx");
        presenter = new BasePersenter(this,this);
        dataDao = XutilsDataDao.getInstance(this);
        list=dataDao.query("constant","bookgarden:user:sms:regist_",SmsMode.class);        close.setOnClickListener(this);
        loinBut.setOnClickListener(this);
        sendCode.setOnClickListener(this);


    }

    private void sendMsg() {
        String name = telPhone.getText().toString();
        if (TextUtils.isEmpty(name) || name.length() != 11) {
            showToast("请输入正确的手机号码");
            return;
        }

        if (!Utlis.isMobileNO(name)) {
            showToast("手机号格式有误");
            return;
        }
        if (null == list || list.size() <= 0) {
            showToast("短信模板错误");
            return;
        }
        LoadingDialog.showMassge(this, "发送中...");
        presenter.loadDataHeader(null, "", Apis.SEND_MSG + name + "/1/" + list.get(0).getKey() + "/6", 1001, Utlis.getHeadler(this), HttpType.GET);


    }

    @Override
    public void onRequestPermissions(String str, boolean z) {

    }


    @Override
    public void returnData(String data, int urlCode) {
        LoadingDialog.hideProgress();

        LogUtil.e("返回数据", data + "");
        if (TextUtils.isEmpty(data)) {
            return;
        }

        handler.obtainMessage(urlCode, data).sendToTarget();
    }

    @Override
    public void LoadError(String errorMsg, int urlCode) {
        if (urlCode == 1001) {
            showToast("请求失败");
        }
        LoadingDialog.hideProgress();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    recLen--;
                    sendCode.setText("已发送(" + recLen + "秒)");
                    if (recLen > 0) {
                        telPhone.setEnabled(false);
//                        telPhone.setClearIconVisible(false);
                        sendCode.setClickable(false);
                        Message message = handler.obtainMessage(1);
                        handler.sendMessageDelayed(message, 1000); // send message
                    } else {
                        sendCode.setText("重新获取");
                        telPhone.setEnabled(true);
                        sendCode.setClickable(true);
                        recLen = 61;
                    }
                    break;

                case 1001:
                    String str = (String) msg.obj;
                    if (TextUtils.isEmpty(str)) {
                        return;
                    }
                    DataBean bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());
                    if (bean.getCode() == 200) {
                        msgCode = bean.getData();
                        handler.sendEmptyMessage(1);

//                        try {
//                            JSONObject object = new JSONObject(bean.getData());
//                            msgCode = object.getString("data");
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
                    }
                    break;

                case 1002:
                    str = (String) msg.obj;
                    bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());
                    if (bean.getCode() == 200) {


                    }
                    break;
                case 1003:
                    str = (String) msg.obj;
                    bean = Utlis.getDataBean(str);
                    showToast(bean.getMessage());
                    if (bean.getCode() == 200) {

                        presenter.loadDataHeader(null,"",Apis.GET_USERINFO,1004,Utlis.getHeadler(BundTellActivity.this), HttpType.GET);

                    }
                    break;
                case 1004:
                    str = (String) msg.obj;
                    LoadingDialog.hideProgress();
                    bean = Utlis.getDataBean(str);
                    if (bean.getCode()==200){

                        MyApplication.getInstance().userInfo = (UserInfo) JsonUitl.stringToObject(bean.getData(), UserInfo.class);
                        SpUtils.getInstance().save(BundTellActivity.this,"userinfo",""+bean.getData());

                        finish();

                    }
                    break;
            }
        }
    };


    private void saveUser(){
        if (!msgCode.equals(smsCode.getText().toString())){
            showToast("验证码正确");
            return;
        }
        Map<String,String> map = new HashMap<>();
        map.put("nickname",wxLoginBean.getNickname());
        map.put("header",wxLoginBean.getHeadimgurl());
        map.put("gender",wxLoginBean.getSex());
        map.put("phone",telPhone.getText().toString());
        map.put("code",wxLoginBean.getOpenid());
        map.put("verifyCode",smsCode.getText().toString());
        presenter.loadData(map,"", Apis.WX_LOGIN_SAVE,1003);
    }

}
